<?php

namespace app\adminapi\controller;

use app\helpers\Common;
use app\common\model\VueAdminRoleUser as AdminRoleUser;
use app\common\model\VueAdminMenu as AdminMenu;

use think\Request;
use think\facade\Db;
use think\Exception;

class Admin extends Base
{
    public function initialize()
    {
        parent::initialize();

        //$this->appName = 'adminapi';
        $this->modelName = 'VueAdmin';
        $this->defaultOrder = 'sorting ASC, created_at DESC';
    }

    /**
     * Info
     */
    public function info(Request $request)
    {
        $param = $request->param();
        if (empty($param['id'])) {
            return api_response(self::STATUS_ERROR, self::NOT_PARAM, '');
        }

        $id = $param['id'];
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $info = $model->find($id);
        if (!$info) {
            return api_response(self::STATUS_ERROR, '不存在！', []);
        }
        $info = $model->formatItem($info, ['format_source' => 'backend']);

        return api_response(self::STATUS_SUCCESS, '', $info);
    }

    /**
     * Save
     */
    public function save(Request $request)
    {
        Db::startTrans();
        try {
            $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
            $model = new $className;

            $data = $this->evalData($request);
            if (isset($data['id']) && $data['id']) {
                $info = $model->where('id', $data['id'])->field('*')->find();
                if (!$info) {
                    return api_response(self::STATUS_ERROR, '不存在', '');
                }
                $data['updated_at'] = time();
                $message = '保存失败';
                $result = $model->where(['id' => $data['id']])->update($data);

                $afterAction = '_after_update';
            } else {
                $data['created_at'] = time();
                $message = '创建失败';
                $result = $model->create($data);
                $data['id'] = $result->id ?? 0;

                $afterAction = '_after_insert';
            }
            if ($result === false) {
                return api_response(self::STATUS_ERROR, $message, []);
            }

            $roleIds = $request->param('role_ids');
            if (isset($data['id']) && $data['id']) {
                AdminRoleUser::where('admin_id', $data['id'])->delete();
            }
            foreach ($roleIds as $roleId) {
                $res = AdminRoleUser::insert(['role_id' => $roleId, 'admin_id' => $data['id']]);
                if ($res === false) {
                    Db::rollback();
                    return api_response(self::STATUS_ERROR, '保存管理员角色失败!', []);
                }
            }

            // Query执行后的操作
            $model->$afterAction($data);
            if (isset($info)) {
                $afterRes = $this->afterUpdate($data, $info);
            } else {
                $afterRes = $this->afterInsert($data);
            }
            if ($afterRes['code'] != 1) {
                return api_response(self::STATUS_ERROR, $afterRes['msg'] ?? 'after error', []);
            }

            Db::commit();
            return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, $data);
        } catch (Exception $e) {
            Db::rollback();
            return api_response(self::STATUS_ERROR, '失败', $e->getMessage());
        }
    }

    /**
     * 设置密码
     */
    public function setPassword(Request $request)
    {
        $param = $request->param();
        if (empty($param['id'])) {
            return api_response(self::STATUS_ERROR, 'ID(id)不能为空', self::NOT_PARAM);
        }
        if (empty($param['password'])) {
            return api_response(self::STATUS_ERROR, '密码(password)不能为空', self::NOT_PARAM);
        }

        $id = $param['id'];
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $info = $model->where('id', $id)->find();
        if (!$info) {
            return api_response(self::STATUS_ERROR, '不存在！', []);
        }
        $password = trim($param['password']);
        $info->password = password_hash($password, PASSWORD_BCRYPT);
        $result = $info->save();
        if ($result === false) {
            return api_response(self::STATUS_ERROR, '失败', '');
        }

        return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, '');
    }

    /**
     * Profile
     */
    public function profile(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $info = $this->admin;
        $info = $model->formatItem($info);

        $menus = $model->getMenus($info['id']);
        $role_routes = [];
        foreach ($menus as $menu) {
            $role_routes[] = $menu['app'] . '/' . $menu['controller'] . '/' . $menu['action'];
            $role_routes[] = $menu['app'] . 'api/' . $menu['controller'] . '/' . $menu['action'];
            if ($menu['route']) {
                $role_routes[] = $menu['route'];
            }
        }
        $info['role_routes'] = $role_routes;
        $route_menus = $model->getMenus($info['id'], true);
        $treeMenus = AdminMenu::toRouteTree($route_menus);
        $async_routes = AdminMenu::treeToRoutes($treeMenus);
        //dump($async_routes);die;
        $info['async_routes'] = $async_routes;

        return api_response(self::STATUS_SUCCESS, '', $info);
    }

    /**
     * 保存个人信息
     */
    public function saveProfile(Request $request)
    {
        $param = $request->param();
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;

        $info = $model->where('id', $this->admin['id'])->find();
        if (!empty($param['avatar'])) {
            $info->avatar = $param['avatar'];
            $this->admin['avatar'] = $param['avatar'];
            $this->admin['full_avatar'] = full_file_url($param['avatar']);
        }
        if (!empty($param['nickname'])) {
            $info->nickname = $param['nickname'];
            $this->admin['nickname'] = $param['nickname'];
        }
        if (!empty($param['phone'])) {
            $info->phone = $param['phone'];
            $this->admin['phone'] = $param['phone'];
        }
        if (!empty($param['email'])) {
            $info->phone = $param['email'];
            $this->admin['email'] = $param['email'];
        }
        if (!empty($param['remark'])) {
            $info->remark = $param['remark'];
            $this->admin['remark'] = $param['remark'];
        }
        $result = $info->save();
        if ($result === false) {
            return api_response(self::STATUS_ERROR, '失败', '');
        }
        cache('auth_admin_id-' . $this->admin['id'], $this->admin, $info['token_expire'], 'admin-auth');

        return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, '');
    }

    /**
     * 修改密码
     */
    public function resetPassword(Request $request)
    {
        $param = $request->param();
        if (empty($param['password'])) {
            return api_response(self::STATUS_ERROR, '原密码(password)不能为空', self::NOT_PARAM);
        }
        if (empty($param['new_password'])) {
            return api_response(self::STATUS_ERROR, '新密码(new_password)不能为空', self::NOT_PARAM);
        }
        /*if (empty($param['confirm_password'])) {
            return api_response(self::STATUS_ERROR, '确认密码(confirm_password)不能为空', self::NOT_PARAM);
        }*/

        $token = $request->header('token');
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $info = $model->where('token', $token)->find();
        if (!$info) {
            return api_response(self::STATUS_ERROR, '不存在！', []);
        }
        $password = trim($param['password']);
        $newPassword = trim($param['new_password']);
        if (!password_verify($password, $info['password'])) {
            return api_response(self::STATUS_ERROR, '原密码不正确！', self::NOT_PARAM);
        }
        $info->password = password_hash($newPassword, PASSWORD_BCRYPT);
        $result = $info->save();
        if ($result === false) {
            return api_response(self::STATUS_ERROR, '失败', '');
        }

        return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, '');
    }

    /**
     * Menu
     */
    public function menu(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $info = $this->admin;
        $info = $model->formatItem($info);

        $route_menus = $model->getMenus($info['id'], true);
        $treeMenus = AdminMenu::toRouteTree($route_menus);
        if ($this->sourceUi == self::SOURCE_UI_2) {
            $async_routes = AdminMenu::treeToRoutesArco($treeMenus);
            $tools_routes = [
                [
                    'path' => '/tools',
                    'name' => 'tools',
                    'component' => '',
                    'meta' => [
                        'locale' => 'tools',
                        'title' => '实用工具',
                        'requiresAuth' => true,
                        'icon' => 'icon-tool',
                        'order' => 1100,
                    ],
                    'children' => [
                        [
                            'path' => '/tools/chart',
                            'name' => 'Chart',
                            'component' => 'test/chart',
                            'meta' => [
                                'locale' => 'tools.chart',
                                'title' => '图表',
                                'requiresAuth' => true,
                            ],
                        ],
                        [
                            'path' => '/tools/test',
                            'name' => 'Test',
                            'component' => 'test/test',
                            'meta' => [
                                'locale' => 'tools.test',
                                'title' => '大数据测试',
                                'requiresAuth' => true,
                            ],
                        ],
                        [
                            'path' => '/tools/form',
                            'name' => 'TestForm',
                            'component' => 'test/form',
                            'meta' => [
                                'locale' => 'tools.testForm',
                                'title' => '表单测试',
                                'requiresAuth' => true,
                            ],
                        ],
                        [
                            'path' => '/tools/table',
                            'name' => 'TestTable',
                            'component' => 'test/table',
                            'meta' => [
                                'locale' => 'tools.testTable',
                                'title' => '表格测试',
                                'requiresAuth' => true,
                            ],
                        ]
                    ],
                ]
            ];
            $async_routes = array_merge($async_routes, $tools_routes);
        } else {
            $async_routes = AdminMenu::treeToRoutes($treeMenus);
        }

        return api_response(self::STATUS_SUCCESS, '', $async_routes);
    }

    /**
     * 检查登录名是否已存在
     */
    public function checkLoginName(Request $request)
    {
        $param = $request->param();
        if (empty($param['username'])) {
            return api_response(self::STATUS_ERROR, self::NOT_PARAM, '');
        }

        $name = $param['username'];
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;
        $where = [
            ['username', '=', $name],
            ['status', '=', 1]
        ];
        $info = $model->where($where)->field('id')->find();
        if ($info) {
            return api_response(1, '存在！', []);
        } else {
            return api_response(0, '不存在！', []);
        }
    }

    /**
     * Eval data for post data save
     *
     * @param Request $request
     * @return array
     */
    protected function evalData($request)
    {
        $param = $request->param();

        $data = [
            'id' => $param['id'],
            'avatar' => $param['avatar'],
            'username' => $param['username'],
            'nickname' => $param['nickname'],
            //'phone' => $param['phone'] ?? '',
            'email' => $param['email'],
            'remark' => $param['remark'],
            'type' => $param['type'] ?? 1,
            'sorting' => $param['sorting'],
            'status' => $param['status'],
        ];

        return $data;
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;

        $data = $model->formatDatas($data, ['format_source' => 'backend']);
//        foreach ($data as $item) {
//            $item = $model->formatItem($item);
//        }

        return $data;
    }

    /**
     * 筛选条件
     */
    protected function getFilterWhere($request)
    {
        $param = $request->param();
        $where = [];
        if (isset($param['username']) && $param['username']) {
            $where[] = ['username', 'like', '%' . trim($param['username']) . '%'];
        }
        if (isset($param['email']) && $param['email']) {
            $where[] = ['email', 'like', '%' . trim($param['email']) . '%'];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = $param['range_date'];
            $startTime = strtotime($rangeDate[0]);
            $endTime = strtotime($rangeDate[1]);
            $where[] = ['created_at', '>=', $startTime];
            $where[] = ['created_at', '<=', $endTime];
        }

        return $where;
    }
}
